const db = require('../config/db');

const getCartByUserId = async (userId) => {
  const [rows] = await db.query(`
    SELECT c.id as cart_id, c.quantity, p.id as product_id, p.name, p.price, p.image
    FROM cart c
    JOIN products p ON c.product_id = p.id
    WHERE c.user_id = ?
  `, [userId]);
  return rows;
};

const addToCart = async (userId, productId, quantity) => {
  // 检查是否已存在
  const [existing] = await db.query(
    'SELECT * FROM cart WHERE user_id = ? AND product_id = ?',
    [userId, productId]
  );
  
  if (existing.length > 0) {
    // 更新数量
    await db.query(
      'UPDATE cart SET quantity = quantity + ? WHERE user_id = ? AND product_id = ?',
      [quantity, userId, productId]
    );
  } else {
    // 新增
    await db.query(
      'INSERT INTO cart (user_id, product_id, quantity) VALUES (?, ?, ?)',
      [userId, productId, quantity]
    );
  }
  
  return getCartByUserId(userId);
};

const updateCartItem = async (userId, productId, quantity) => {
  await db.query(
    'UPDATE cart SET quantity = ? WHERE user_id = ? AND product_id = ?',
    [quantity, userId, productId]
  );
  return getCartByUserId(userId);
};

const removeFromCart = async (userId, productId) => {
  await db.query(
    'DELETE FROM cart WHERE user_id = ? AND product_id = ?',
    [userId, productId]
  );
  return getCartByUserId(userId);
};

const clearCart = async (userId) => {
  await db.query('DELETE FROM cart WHERE user_id = ?', [userId]);
};

module.exports = {
  getCartByUserId,
  addToCart,
  updateCartItem,
  removeFromCart,
  clearCart
};